//
//  YLCSendView.m
//  YouLe
//
//  Created by 初程程 on 2018/1/5.
//  Copyright © 2018年 初程程. All rights reserved.
//

#import "YLCSendView.h"
#import "YLCInputCutView.h"
#import <ReactiveCocoa/RACReturnSignal.h>
#import "YLCKeyBoardToolBarView.h"
#import "ImagePicker.h"
#import "YLCSendTieziSuccessViewController.h"
@interface YLCSendView()<UITextFieldDelegate,YYTextViewDelegate,UIActionSheetDelegate>
@end
@implementation YLCSendView
{
    UITextField *titleField;
    UIImageView *verLineView;
    YYTextView *contentView;
    YLCKeyBoardToolBarView *toolBar;
    NSString *textViewText;
    NSMutableAttributedString *contentAttriStr;
    NSString *contentString;
    NSInteger imageNumber;
    BOOL shouldShowTool;
    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
- (void)removeNotification{
    self.hiddenNoti = YES;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        imageNumber = -1;
        self.backgroundColor = [UIColor whiteColor];
        
        [self addNoti];
        [self createCustomViews];
    }
    return self;
}
- (void)addNoti{
    self.hiddenNoti = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}
- (void)sendText{
    
    YLCAccountModel *userModel = [[YLCAccountManager shareManager] currentAccount];
    if (![YLCLoginManager checkLoginStateWithTarget:self]) {
        return;
    }
    
    
    if (JK_IS_STR_NIL(titleField.text)) {
        [SVProgressHUD showErrorWithStatus:@"请输入标题"];
        return;
    }
    if (JK_IS_STR_NIL(contentView.text)) {
        [SVProgressHUD showErrorWithStatus:@"请输入内容"];
        return;
    }
    
    contentString = contentView.text;
    
    NSArray *attachmentRanges = contentView.textLayout.attachmentRanges;
    
    NSArray *attachments = contentView.textLayout.attachments;

    for (int index = 0; index<attachmentRanges.count; index++) {
        NSValue *rangeValue = attachmentRanges[index];
        NSRange range = [rangeValue rangeValue];
        NSString *insertString = [NSString stringWithFormat:@"{%d}",index];
        NSMutableString *changeString = contentString.mutableCopy;
        [changeString insertString:insertString atIndex:range.location+index*insertString.length];
        contentString = changeString.copy;
    }
    NSMutableArray *imgContainer = [NSMutableArray arrayWithCapacity:0];
    for (YYTextAttachment *attachment in attachments) {
        
        UIImage *contentImage = attachment.content;
        
        [imgContainer addObject:contentImage];
    }
    NSMutableArray *baseContainerArr = [NSMutableArray arrayWithCapacity:0];
    
    for (UIImage *photo in imgContainer) {

        NSString *photoString = @"";

        photoString = [photo base64String];
        
        [baseContainerArr addObject:[NSString stringWithFormat:@"data:image/jpeg;base64,%@",photoString]];
    }
    
    [YLCNetWorking loadNetServiceWithParam:@{@"token":userModel.token,@"userId":userModel.user_id,@"content":contentString,@"title":titleField.text,@"Imgdata":baseContainerArr.copy} method:@"POST" urlPath:@"app/forum/doSave" delegate:self response:^(id responseObject, NSError *error) {
        if (error) {
            return ;
        }
//        [SVProgressHUD showSuccessWithStatus:@"发布成功!"];
        YLCSendTieziSuccessViewController *con = [[YLCSendTieziSuccessViewController alloc] init];
        
        [(UINavigationController *)[YLCFactory currentNav] pushViewController:con animated:YES];
    }];
}
- (void)createCustomViews{
    titleField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, self.frameWidth, 40)];
    
    titleField.placeholder = @"标题（最多30个字）";

    titleField.font = [UIFont systemFontOfSize:14];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 40)];

    titleField.leftView = leftView;

    titleField.leftViewMode = UITextFieldViewModeAlways;
    
    titleField.delegate = self;
    
    RACSignal *titleSignal = [titleField.rac_textSignal bind:^RACStreamBindBlock{
        return ^RACStream *(id value, BOOL *stop){
            shouldShowTool = NO;
            [self dissMiss];

            return [RACReturnSignal return:value];
        };
    }];
    
    [titleSignal subscribeNext:^(id x) {
        NSString *text = x;
    }];
    
    [self addSubview:titleField];
    
    verLineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, titleField.frameMaxY, self.frameWidth, 0.5)];
    
    verLineView.backgroundColor = YLC_GRAY_COLOR;
    
    [self addSubview:verLineView];
    
    contentView = [YYTextView new];
    
    contentView.frame = CGRectMake(18, verLineView.frameMaxY, self.frameWidth-36, self.frameHeight-verLineView.frameMaxY);
    
    contentView.font = [UIFont systemFontOfSize:14];
    
    contentView.placeholderText = @"#分享是一种美德，能给大家带来快乐...";
    
    contentView.placeholderFont = [UIFont systemFontOfSize:14];
    
    contentView.delegate = self;
    
    [self addSubview:contentView];
    
    toolBar = [[YLCKeyBoardToolBarView alloc] initWithFrame:CGRectMake(0, kScreenHeight, self.frameWidth, 40)];
    
    [toolBar.imageSigal subscribeNext:^(id x) {
        [self showImageSheet];
    }];
    
    toolBar.backgroundColor = YLC_COMMON_BACKCOLOR;
    
//    [self addSubview:toolBar];
}
- (void)showImageSheet{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
    
    [sheet showInView:self];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    [[ImagePicker sharedManager] dwSetPresentDelegateVC:[YLCFactory currentNav] SheetShowInView:self InfoDictionaryKeys:buttonIndex];
    
    //回调
    [[ImagePicker sharedManager] dwGetpickerTypeStr:^(NSString *pickerTypeStr) {
        
        
        
    } pickerImagePic:^(UIImage *pickerImagePic) {
        [self addImageToTextViewWithImage:pickerImagePic];
    }];
    
}
- (void)addImageToTextViewWithImage:(UIImage *)image{
//    CGSizeMake(contentView.frameWidth, image.size.height*(contentView.frameWidth/image.size.width)
    CGSize imageSize = image.size;
    if (image.size.height>150) {
        
//        image = [self imageWithImageSimple:image scaledToSize:];
        imageSize = CGSizeMake(contentView.frameWidth*(150/contentView.frameHeight), 150);
    }
    imageNumber +=1;
    
//    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:contentView.text];
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString:contentView.attributedText];
    
    text.yy_font = [UIFont systemFontOfSize:14];
    
    UIFont *font = [UIFont systemFontOfSize:14];
    
    NSMutableAttributedString *attachment = nil;
    
    NSMutableAttributedString *lineBreakKey2 = [[NSMutableAttributedString alloc] initWithString:@"\n"];
    
    lineBreakKey2.yy_font = font;
    
    [text appendAttributedString:lineBreakKey2];
    
    attachment = [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeScaleAspectFit attachmentSize:imageSize alignToFont:font alignment:YYTextVerticalAlignmentCenter];
    
    [text appendAttributedString:attachment];
    
    NSMutableAttributedString *lineBreakKey = [[NSMutableAttributedString alloc] initWithString:@"\n"];
    
    lineBreakKey.yy_font = font;
    
    [text appendAttributedString:lineBreakKey];
    
    contentView.attributedText = text;
    
    [contentView becomeFirstResponder];
}
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize

{
    
    // Create a graphics image context
    
    UIGraphicsBeginImageContext(newSize);
    
    
    
    // Tell the old image to draw in this new context, with the desired
    
    // new size
    
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    
    
    // Get the new image from the context
    
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    
    
    // End the context
    
    UIGraphicsEndImageContext();
    
    
    
    // Return the new image.
    
    return newImage;
    
}
- (void)keyboardWillHide:(NSNotification *)notification{
    NSDictionary *userInfo = notification.userInfo;
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [toolBar dissMissWithDuration:duration];
}
- (void)keyboardDidHide:(NSNotification *)notification{
    
}
- (void)keyboardDidShow:(NSNotification *)notification{

}
- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *userInfo = notification.userInfo;
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    if (shouldShowTool) {
        [toolBar showWithDuration:duration rect:keyboardF];
    }
}
- (void)textViewDidChange:(YYTextView *)textView{

    NSLog(@"%@",textView.text);
}
- (BOOL)textViewShouldBeginEditing:(YYTextView *)textView{
    shouldShowTool = YES;
    
    return YES;
    
}
- (void)dissMiss{
    [UIView animateWithDuration:0.25
                          delay:0.0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{
                         
                         toolBar.frame = CGRectMake(0, kScreenHeight, self.frameWidth, 40);
                     }
                     completion:^(BOOL finished) {
                         
                     }];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString *nowText = textField.text;
    if (nowText.length>=50) {
        if (nowText.length==50) {
            if (![YLCFactory isStringOk:string]) {
                return YES;
            }
        }
        return NO;
    }
    return YES;
}
- (void)layoutSubviews{
    [super layoutSubviews];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
